const BluetoothManager = require('../../utils/bluetooth.js');
const api = require('../../utils/api.js');
const app = getApp();

Page({
  data: {
    // 设备连接状态
    deviceConnected: false,
    deviceName: '',
    scanning: false,
    battery: 0,
    impedance: 0, // 添加阻抗值
    actualCurrent: 0, // 实际电流值
    
    // 治疗参数
    treatmentParams: {
      mode: 'tDCS+',
      current: 0.1,
      time: 20,
      frequency: 10.0
    },
    
    // 格式化后的治疗参数（用于显示）
    formattedTreatmentParams: {
      current: '0.00', // 2位小数以显示0.10mA
      frequency: '0.0'
    },
    
    // 治疗状态
    treatmentActive: false,
    treatmentPaused: false,
    remainingTime: 0,
    formattedRemainingTime: '00:00', // 添加格式化后的时间显示
    treatmentTimer: null,
    
    // 设备扫描
    showDeviceModal: false,
    scannedDevices: [],
    
    // 用户模板
    userTemplates: [],
    
    // 模板类型
    templateTypes: [
      { key: 'hospital', name: '医院' },
      { key: 'school', name: '学校' },
      { key: 'enterprise', name: '企业' },
      { key: 'research', name: '科研' }
    ],
    currentTemplateType: 'hospital', // 默认模板类型
    
    // 格式化后的用户模板（用于显示）
    formattedUserTemplates: [],
    
    // 模板tab切换
    currentTemplateTab: 'user', // 'user' 或 'system'
    
    // 系统模板
    systemTemplates: [
    ]
  },
  
  // 防抖定时器
  debounceTimer: null,

  onLoad(options) {
    if  (options.currentTemplateType){
      this.setData({
        currentTemplateType: options.currentTemplateType
      });
      // 根据模板类型加载模板
      setTimeout(() => {
        this.loadTemplatesByType(this.data.currentTemplateType);
      }, 2200);
    } else{
      // 加载用户模板
      setTimeout(() => {
        this.loadUserTemplates();
        this.loadSystemTemplates();
      }, 2200);

    }
    // 初始化蓝牙管理器
    this.bluetoothManager = new BluetoothManager();
    this.setupBluetoothCallbacks();
   
    
    
  },

  onShow() {
    // 刷新连接状态
    // this.checkConnectionStatus();
  },

  onUnload() {
    // 清理定时器
    if (this.data.treatmentTimer) {
      clearInterval(this.data.treatmentTimer);
    }
    
    // 清理防抖定时器
    if (this.debounceTimer) {
      clearTimeout(this.debounceTimer);
    }
  },

  // 分享给朋友
  onShareAppMessage(res) {
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log('来自页面内转发按钮');
    }
    return {
      title: '智能盆底治疗仪 - 专业tDCS治疗',
      path: '/pages/index/index',
      success: function(res) {
        console.log('分享成功', res);
        wx.showToast({
          title: '分享成功',
          icon: 'success'
        });
      },
      fail: function(res) {
        console.log('分享失败', res);
        wx.showToast({
          title: '分享失败',
          icon: 'none'
        });
      }
    };
  },

  // 分享到朋友圈
  onShareTimeline() {
    return {
      title: '智能盆底治疗仪 - 专业tDCS治疗',
      query: ''
    };
  },
  async loadSystemTemplates() { 
      const res = await api.request('/treatments/templates', {
        method: 'GET',
        data: {
          type: 'system'
        }
      });
      this.setData({
        systemTemplates: res.records
      });
  },
  async loadTemplatesByType (type) {
    try {
      // 检查用户是否已登录
      const token = wx.getStorageSync('token');
      if (!token) {
        wx.showToast({
          title: '请先登录',
          icon: 'none'
        });
        return;
      }
      
      const res = await api.getTemplatesByType(type);
      this.setData({
        userTemplates: res.templates,
        
      });
    } catch (error) {
      console.error('加载模板失败:', error);
      if (error.message && error.message.includes('401')) {
        wx.showToast({
          title: '请先登录',
          icon: 'none'
        });
      } else {
        wx.showToast({
          title: '加载模板失败',
          icon: 'none'
        });
      }
    }
  },

  // 设置蓝牙回调
  setupBluetoothCallbacks() {
    this.bluetoothManager.setCallbacks({
      onStatusUpdate: (status) => {
        console.log('设备状态更新:', status);
        this.setData({
          treatmentActive: status.working,
          treatmentPaused: false // 暂停状态由APP控制
        });
      },
      onBatteryUpdate: (battery) => {
        console.log('电池状态更新:', battery);
        this.setData({
          battery: Math.round(battery.level)
        });
      },
      onImpedanceUpdate: (impedance) => {
        console.log('阻抗值更新:', impedance);
        this.setData({
          impedance: impedance.toFixed(1)
        });
      },
      onActualCurrentUpdate: (current) => {
        console.log('实际电流更新:', current);
        this.setData({
          actualCurrent: current.toFixed(2)
        });
      },
      onFaultUpdate: (fault) => {
        console.log('故障信息更新:', fault);
        // 检查故障位域
        if (fault & 0x01) { // 过流保护
          wx.showModal({
            title: '警告',
            content: '检测到过流保护，请检查设备连接',
            showCancel: false
          });
          this.stopTreatment();
        }
        if (fault & 0x02) { // 阻抗过高
          wx.showModal({
            title: '警告',
            content: '检测到阻抗过高，请检查电极连接',
            showCancel: false
          });
        }
        if (fault & 0x04) { // 过压保护
          wx.showModal({
            title: '警告',
            content: '检测到过压保护，请检查电源',
            showCancel: false
          });
        }
        if (fault & 0x10) { // 电池电量低
          wx.showToast({
            title: '电池电量低',
            icon: 'none'
          });
        }
      }
    });
  },

  // 检查连接状态
  async checkConnectionStatus() {
    this.setData({
      deviceConnected: this.bluetoothManager.connected
    });
    
    if (this.bluetoothManager.connected) {
      try {
        // 查询电池状态 - 分开发送命令
        await this.bluetoothManager.queryBattery();
      } catch (error) {
        console.error('查询电池状态失败:', error);
      }
    }
  },
  // 扫描并连接设备
  async scanAndConnect() {
    try {
      this.setData({ scanning: true });
      
      // 初始化蓝牙
      await this.bluetoothManager.initBluetooth();
      
      // 扫描设备
      const devices = await this.bluetoothManager.scanDevices();
      
      if (devices.length === 0) {
        wx.showToast({
          title: '未发现设备',
          icon: 'none'
        });
        this.setData({ scanning: false });
        return;
      }
      
        this.setData({
          scannedDevices: devices,
          showDeviceModal: true,
          scanning: false
        });
    } catch (error) {
      console.error('扫描设备失败:', error);
      wx.showToast({
        title: '扫描失败',
        icon: 'none'
      });
      this.setData({ scanning: false });
    }
  },

  // 连接到指定设备
  async connectToDevice(e) {
    const device = e.currentTarget.dataset.device;
    
    try {
      wx.showLoading({ title: '连接中...' });
      
      await this.bluetoothManager.connectDevice(device.deviceId);
      
      this.setData({
        deviceName: device.name,
        deviceConnected: true,
        showDeviceModal: false
      });
      
      // 更新全局状态
      app.globalData.deviceConnected = true;
      app.globalData.deviceId = device.deviceId;
      
      wx.hideLoading();
      wx.showToast({
        title: '连接成功',
        icon: 'success'
      });
      
      // 查询设备状态 - 分开发送命令，避免同时发送
      setTimeout(async () => {
        try {
          await this.bluetoothManager.queryBattery();
          // 延迟500ms后再发送下一个命令
          await new Promise(resolve => setTimeout(resolve, 500));
          await this.bluetoothManager.queryImpedance();
        } catch (error) {
          console.error('查询设备状态失败:', error);
        }
      }, 1000);
      
    } catch (error) {
      console.error('连接设备失败:', error);
      wx.hideLoading();
      wx.showToast({
        title: '连接失败',
        icon: 'none'
      });
    }
  },

  // 断开设备连接
  disconnectDevice() {
    wx.showModal({
      title: '确认断开',
      content: '确定要断开设备连接吗？',
      success: (res) => {
        if (res.confirm) {
          this.bluetoothManager.disconnect();
          this.setData({
            deviceConnected: false,
            treatmentActive: false,
            treatmentPaused: false
          });
          
          // 更新全局状态
          app.globalData.deviceConnected = false;
          app.globalData.deviceId = '';
          
          // 停止治疗计时器
          if (this.data.treatmentTimer) {
            clearInterval(this.data.treatmentTimer);
            this.setData({ treatmentTimer: null });
          }
          
          wx.showToast({
            title: '已断开连接',
            icon: 'success'
          });
        }
      }
    });
  },

  // 选择治疗模式
  selectMode(e) {
    const mode = e.currentTarget.dataset.mode;
    this.setData({
      'treatmentParams.mode': mode
    });
    
    // 更新全局数据
    app.globalData.treatmentParams.mode = mode;
    
    // 实时发送到蓝牙设备（带防抖）
    this.debounceSendTreatmentParams();
  },

  // 电流强度变化
  onCurrentChange(e) {
    const current = parseFloat(e.detail.value);
    // 限制电流强度范围在0-2mA
    const limitedCurrent = Math.min(Math.max(current, 0), 2);
    this.setData({
      'treatmentParams.current': limitedCurrent,
      'formattedTreatmentParams.current': limitedCurrent.toFixed(2) // 3位小数以显示0.001mA
    });
    
    // 更新全局数据
    app.globalData.treatmentParams.current = limitedCurrent;
    
    // 实时发送到蓝牙设备（带防抖）
    this.debounceSendTreatmentParams();
  },

  // 增加电流强度
  increaseCurrent() {
    let current = this.data.treatmentParams.current + 0.04; // 步进0.04mA
    if (current > 2) current = 2;
    this.setData({
      'treatmentParams.current': current,
      'formattedTreatmentParams.current': current.toFixed(2) // 3位小数以显示0.001mA
    });
    
    // 更新全局数据
    app.globalData.treatmentParams.current = current;
    
    // 实时发送到蓝牙设备（带防抖）
    this.debounceSendTreatmentParams();
  },

  // 减少电流强度
  decreaseCurrent() {
    let current = this.data.treatmentParams.current - 0.04; // 步进0.04mA
    if (current < 0) current = 0;
    this.setData({
      'treatmentParams.current': current,
      'formattedTreatmentParams.current': current.toFixed(2) // 3位小数以显示0.001mA
    });
    
    // 更新全局数据
    app.globalData.treatmentParams.current = current;
    
    // 实时发送到蓝牙设备（带防抖）
    this.debounceSendTreatmentParams();
  },

  // 选择治疗时间
  selectTime(e) {
    const time = parseInt(e.currentTarget.dataset.time);
    this.setData({
      'treatmentParams.time': time
    });
    
    // 更新全局数据
    app.globalData.treatmentParams.time = time;
    
    // 实时发送到蓝牙设备（带防抖）
    this.debounceSendTreatmentParams();
  },

  // 频率变化（滑动条）
  onFrequencyChange(e) {
    const frequency = parseFloat(e.detail.value);
    // 限制频率范围在0.1-100Hz
    const limitedFrequency = Math.min(Math.max(frequency, 0.1), 100);
    this.setData({
      'treatmentParams.frequency': limitedFrequency,
      'formattedTreatmentParams.frequency': limitedFrequency.toFixed(1)
    });
    
    // 更新全局数据
    app.globalData.treatmentParams.frequency = limitedFrequency;
    
    // 实时发送到蓝牙设备（带防抖）
    this.debounceSendTreatmentParams();
  },

  // 增加频率
  increaseFrequency() {
    let frequency = parseFloat(this.data.treatmentParams.frequency) + 0.1; // 步进0.1Hz
    if (frequency > 100.0) frequency = 100.0;
    
    frequency = parseFloat(frequency.toFixed(1));

    this.setData({
      'treatmentParams.frequency': frequency,
      'formattedTreatmentParams.frequency': frequency.toFixed(1)
    });
    
    // 更新全局数据
    app.globalData.treatmentParams.frequency = frequency;
    
    // 实时发送到蓝牙设备（带防抖）
    this.debounceSendTreatmentParams();
  },

  // 减少频率
  decreaseFrequency() {
    let frequency = parseFloat(this.data.treatmentParams.frequency) - 0.1; // 步进0.1Hz
    if (frequency < 0.1) frequency = 0.1;
    frequency = parseFloat(frequency.toFixed(1));
    this.setData({
      'treatmentParams.frequency': frequency,
      'formattedTreatmentParams.frequency': frequency.toFixed(1)
    });
    
    // 更新全局数据
    app.globalData.treatmentParams.frequency = frequency;
    
    // 实时发送到蓝牙设备（带防抖）
    this.debounceSendTreatmentParams();
  },

  // 开始治疗
  async startTreatment() {
    if (!this.data.deviceConnected) {
      wx.showToast({
        title: '请先连接设备',
        icon: 'none'
      });
      return;
    }

    try {
      wx.showLoading({ title: '启动中...' });
      
      // 设置治疗参数
      await this.bluetoothManager.setTreatmentParams(this.data.treatmentParams);
      
      // 开始治疗
      await this.bluetoothManager.startTreatment();
      
      // 更新状态
      const initialTime = this.data.treatmentParams.time * 60;
      this.setData({
        treatmentActive: true,
        treatmentPaused: false,
        remainingTime: initialTime,
        formattedRemainingTime: this.formatTime(initialTime) // 初始化格式化时间
      });
      
      // 开始计时
      this.startTreatmentTimer();
      
      wx.hideLoading();
      wx.showToast({
        title: '治疗已开始',
        icon: 'success'
      });
      
    } catch (error) {
      console.error('开始治疗失败:', error);
      wx.hideLoading();
      wx.showToast({
        title: '启动失败',
        icon: 'none'
      });
    }
  },

  // 暂停治疗
  async pauseTreatment() {
    try {
      await this.bluetoothManager.pauseTreatment();
      this.setData({ treatmentPaused: true });
      
      // 暂停计时器
      if (this.data.treatmentTimer) {
        clearInterval(this.data.treatmentTimer);
        this.setData({ treatmentTimer: null });
      }
      
      wx.showToast({
        title: '治疗已暂停',
        icon: 'success'
      });
    } catch (error) {
      console.error('暂停治疗失败:', error);
      wx.showToast({
        title: '暂停失败',
        icon: 'none'
      });
    }
  },

  // 继续治疗
  async resumeTreatment() {
    try {
      await this.bluetoothManager.resumeTreatment();
      this.setData({ treatmentPaused: false });
      
      // 恢复计时器
      this.startTreatmentTimer();
      
      wx.showToast({
        title: '治疗已继续',
        icon: 'success'
      });
    } catch (error) {
      console.error('继续治疗失败:', error);
      wx.showToast({
        title: '继续失败',
        icon: 'none'
      });
    }
  },

  // 停止治疗
  async stopTreatment() {
    wx.showModal({
      title: '确认停止',
      content: '确定要停止当前治疗吗？',
      success: async (res) => {
        if (res.confirm) {
          try {
            await this.bluetoothManager.stopTreatment();
            
            // 计算实际治疗时长
            const totalTime = this.data.treatmentParams.time * 60;
            const actualDuration = (totalTime - this.data.remainingTime) / 60;
            
            // 保存治疗记录
            app.saveTreatmentRecord(this.data.treatmentParams, actualDuration, app.globalData.deviceId);
            
            // 重置状态
            this.setData({
              treatmentActive: false,
              treatmentPaused: false,
              remainingTime: 0,
              formattedRemainingTime: '00:00'
            });
            
            // 停止计时器
            if (this.data.treatmentTimer) {
              clearInterval(this.data.treatmentTimer);
              this.setData({ treatmentTimer: null });
            }
            
            wx.showToast({
              title: '治疗已停止',
              icon: 'success'
            });
            
          } catch (error) {
            console.error('停止治疗失败:', error);
            wx.showToast({
              title: '停止失败',
              icon: 'none'
            });
          }
        }
      }
    });
  },

  // 紧急停止治疗
  async emergencyStop() {
    wx.showModal({
      title: '紧急停止',
      content: '确定要紧急停止当前治疗吗？',
      confirmColor: '#f44336',
      success: async (res) => {
        if (res.confirm) {
          try {
            // 发送紧急停止命令到设备
            await this.bluetoothManager.emergencyStop();
            
            // 计算实际治疗时长
            const totalTime = this.data.treatmentParams.time * 60;
            const actualDuration = (totalTime - this.data.remainingTime) / 60;
            
            // 保存治疗记录
            app.saveTreatmentRecord(this.data.treatmentParams, actualDuration, app.globalData.deviceId);
            
            // 重置状态
            this.setData({
              treatmentActive: false,
              treatmentPaused: false,
              remainingTime: 0,
              formattedRemainingTime: '00:00'
            });
            
            // 停止计时器
            if (this.data.treatmentTimer) {
              clearInterval(this.data.treatmentTimer);
              this.setData({ treatmentTimer: null });
            }
            
            wx.showToast({
              title: '治疗已紧急停止',
              icon: 'success'
            });
            
          } catch (error) {
            console.error('紧急停止治疗失败:', error);
            wx.showToast({
              title: '停止失败',
              icon: 'none'
            });
          }
        }
      }
    });
  },

  // 开始治疗计时器
  startTreatmentTimer() {
    const timer = setInterval(() => {
      const remainingTime = this.data.remainingTime - 1;
      
      if (remainingTime <= 0) {
        // 治疗完成
        this.treatmentComplete();
      } else {
        // 同时更新剩余时间和格式化后的时间
        this.setData({ 
          remainingTime: remainingTime,
          formattedRemainingTime: this.formatTime(remainingTime)
        });
      }
    }, 1000);
    
    this.setData({ treatmentTimer: timer });
  },

  // 治疗完成
  async treatmentComplete() {
    try {
      await this.bluetoothManager.stopTreatment();
      
      // 保存治疗记录
      app.saveTreatmentRecord(this.data.treatmentParams, this.data.treatmentParams.time, app.globalData.deviceId);
      
      // 重置状态
      this.setData({
        treatmentActive: false,
        treatmentPaused: false,
        remainingTime: 0,
        formattedRemainingTime: '00:00'
      });
      
      // 停止计时器
      if (this.data.treatmentTimer) {
        clearInterval(this.data.treatmentTimer);
        this.setData({ treatmentTimer: null });
      }
      
      wx.showModal({
        title: '治疗完成',
        content: '恭喜您完成了本次治疗！',
        showCancel: false,
        confirmText: '确定'
      });
      
    } catch (error) {
      console.error('治疗完成处理失败:', error);
    }
  },

  // 格式化时间显示
  formatTime(seconds) {
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    
    // 使用自定义padStart实现替代padStart方法
    const padStart = (num, length) => {
      let str = num.toString();
      while (str.length < length) {
        str = '0' + str;
      }
      return str;
    };
    
    return `${padStart(mins, 2)}:${padStart(secs, 2)}`;
  },

  // 加载用户模板
  async loadUserTemplates() {
    try {
      // 检查用户是否已登录
      const token = wx.getStorageSync('token');
      if (!token) {
        wx.showToast({
          title: '请先登录',
          icon: 'none'
        });
        return;
      }
      
      const res = await api.getUserTemplates();
      
      this.setData({ userTemplates: res.templates });
    } catch (error) {
      console.error('加载用户模板失败:', error);
      if (error.message && error.message.includes('401')) {
        wx.showToast({
          title: '请先登录',
          icon: 'none'
        });
      } else {
        wx.showToast({
          title: '加载模板失败',
          icon: 'none'
        });
      }
    }
  },

  // 加载模板
  loadTemplate(e) {
    const template = e.currentTarget.dataset.template;
    this.setData({
      treatmentParams: {
        mode: template.treatment_mode,
        current: template.current_intensity,
        time: template.treatment_duration,
        frequency: template.frequency
      },
      formattedTreatmentParams: {
        current: template.current_intensity.toFixed(2),
        frequency: template.frequency.toFixed(1)
      }
    });
    
    // 更新全局数据
    app.globalData.treatmentParams = { 
      mode: template.treatment_mode,
      current: template.current_intensity,
      time: template.treatment_duration,
      frequency: template.frequency
    };
    
    wx.showToast({
      title: '模板已加载',
      icon: 'success'
    });
  },

  // 保存当前参数为模板
  saveCurrentAsTemplate() {
    this.saveElectricalTemplate();
    return

    wx.showActionSheet({
      itemList: ['保存为电刺激治疗方案', '保存为音乐治疗方案'],
      itemColor: '#1396db',
      success: (res) => {
        if (res.tapIndex === 0) {
          // 保存为电刺激治疗方案
          this.saveElectricalTemplate();
        } else if (res.tapIndex === 1) {
          // 保存为音乐治疗方案
          this.saveMusicTemplate();
        }
      }
    });
  },

  // 保存电刺激治疗方案
  saveElectricalTemplate() {
    wx.showModal({
      title: '保存治疗方案',
      content: '请输入方案名称',
      editable: true,
      placeholderText: '例如：我的常用参数',
      success: async (res) => {
        if (res.confirm && res.content) {
          try {
            // 检查用户是否已登录
            const token = wx.getStorageSync('token');
            if (!token) {
              wx.showToast({
                title: '请先登录',
                icon: 'none'
              });
              return;
            }
            
            // 保存到服务器
            const templateData = {
              template_name: res.content,
              template_type: 'hospital', // 默认类型
              treatment_mode: this.data.treatmentParams.mode,
              current_intensity: this.data.treatmentParams.current,
              treatment_duration: this.data.treatmentParams.time,
              frequency: this.data.treatmentParams.frequency
            };
            
            const response = await api.createTreatmentTemplate(templateData);
            
            // 更新页面数据
            this.loadUserTemplates()
            
            wx.showToast({
              title: '方案已保存',
              icon: 'success'
            });
          } catch (error) {
            console.error('保存方案失败:', error);
            if (error.message && error.message.includes('401')) {
              wx.showToast({
                title: '请先登录',
                icon: 'none'
              });
            } else {
              wx.showToast({
                title: '保存失败',
                icon: 'none'
              });
            }
          }
        }
      }
    });
  },

  // 保存音乐治疗方案
  saveMusicTemplate() {
    wx.showModal({
      title: '保存音乐方案',
      content: '请输入方案名称',
      editable: true,
      placeholderText: '例如：放松音乐方案',
      success: (res) => {
        if (res.confirm && res.content) {
          try {
            // 这里应该获取当前选择的音乐播放列表
            // 暂时用模拟数据
            const musicTemplate = {
              id: Date.now(),
              name: res.content,
              type: 'music',
              // 这里应该包含实际的音乐播放列表信息
              playlist: '身心放松音乐',
              playMode: 'sequence',
              createdAt: new Date().toISOString()
            };
            
            // 保存到本地存储
            const templates = wx.getStorageSync('musicTemplates') || [];
            templates.push(musicTemplate);
            wx.setStorageSync('musicTemplates', templates);
            
            wx.showToast({
              title: '音乐方案已保存',
              icon: 'success'
            });
          } catch (error) {
            console.error('保存音乐方案失败:', error);
            wx.showToast({
              title: '保存失败',
              icon: 'none'
            });
          }
        }
      }
    });
  },

  // 删除模板
  deleteTemplate(e) {
    const templateId = e.currentTarget.dataset.id;
    
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这个参数模板吗？',
      success: async (res) => {
        if (res.confirm) {
          try {
            // 检查用户是否已登录
            const token = wx.getStorageSync('token');
            if (!token) {
              wx.showToast({
                title: '请先登录',
                icon: 'none'
              });
              return;
            }
            
            // 从服务器删除模板
            await api.deleteTreatmentTemplate(templateId);
            
            // 重新加载模板列表
            this.loadUserTemplates();
            
            wx.showToast({
              title: '删除成功',
              icon: 'success'
            });
          } catch (error) {
            console.error('删除模板失败:', error);
            if (error.message && error.message.includes('401')) {
              wx.showToast({
                title: '请先登录',
                icon: 'none'
              });
            } else {
              wx.showToast({
                title: '删除失败',
                icon: 'none'
              });
            }
          }
        }
      }
    });
  },

  // 关闭设备选择弹窗
  closeDeviceModal() {
    this.setData({
      showDeviceModal: false,
      scanning: false
    });
  },

  // 重新扫描设备
  async rescanDevices() {
    try {
      this.setData({ scanning: true });
      const devices = await this.bluetoothManager.scanDevices();
      this.setData({
        scannedDevices: devices,
        scanning: false
      });
    } catch (error) {
      console.error('重新扫描失败:', error);
      this.setData({ scanning: false });
      wx.showToast({
        title: '扫描失败',
        icon: 'none'
      });
    }
  },

  // 切换模板tab
  switchTemplateTab(e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({
      currentTemplateTab: tab
    });
  },
  
  // 防抖发送治疗参数
  debounceSendTreatmentParams() {
    // 只有在设备已连接时才发送（移除了治疗状态的限制）
    if (!this.data.deviceConnected) {
      return;
    }
    
    // 清除之前的定时器
    if (this.debounceTimer) {
      clearTimeout(this.debounceTimer);
    }
    
    // 设置新的定时器，300ms后发送
    this.debounceTimer = setTimeout(() => {
      this.bluetoothManager.setTreatmentParams(this.data.treatmentParams);
    }, 300);
  }
});